import axios from 'axios';
import { ElMessage } from 'element-plus';
import { API_CONFIG, HTTP_STATUS, BUSINESS_CODE } from './config.js';
import { useRouter } from 'vue-router'; // 导入路由

// 创建路由实例（注意：在非组件中使用需特殊处理，见下方说明）
const router = useRouter();

// 创建axios实例
const axiosInstance = axios.create({
  baseURL: API_CONFIG.BASE_URL,
  timeout: API_CONFIG.TIMEOUT,
  headers: {
    ...API_CONFIG.HEADERS,
    'Accept': '*/*',
    'Content-Type': 'application/json',
    // 移除初始化时的satoken设置，改为在拦截器中动态添加
  },
  withCredentials: false,
  crossDomain: true,
  timestamp: false
});

// 请求拦截器：每次请求前动态添加最新Token
axiosInstance.interceptors.request.use(
    (config) => {
      // 1. 每次请求前都从localStorage获取最新Token
      const latestToken = localStorage.getItem('satoken');
      if (latestToken) {
        config.headers['satoken'] = latestToken; // 覆盖请求头中的Token
      }

      // 2. 添加时间戳防止缓存
      if (config.method === 'get') {
        config.params = {
          ...config.params,
          _t: Date.now()
        };
      }

      console.log('API Request:', config.method?.toUpperCase(), config.url, config.data || config.params);
      return config;
    },
    (error) => {
      console.error('Request Error:', error);
      return Promise.reject(error);
    }
);

// 响应拦截器：处理Token过期等问题
axiosInstance.interceptors.response.use(
    (response) => {
      console.log('API Response:', response.status, response.data);

      // 3. 如果后端返回了新的Token（如刷新Token机制），更新存储
      if (response.headers['new-satoken']) {
        localStorage.setItem('satoken', response.headers['new-satoken']);
      }

      if (response.status >= 200 && response.status < 300) {
        return response.data;
      }

      throw new Error(`HTTP Error: ${response.status} ${response.statusText}`);
    },
    (error) => {
      console.error('API Error:', error);

      let message = '网络请求失败';

      if (error.response) {
        const { status, data } = error.response;

        switch (status) {
          case HTTP_STATUS.UNAUTHORIZED:
            message = '登录已过期，请重新登录';
            // 4. Token过期时，清除存储并跳转登录页
            localStorage.removeItem('satoken');
            localStorage.removeItem('isAuthenticated');
            router.push('/login'); // 跳转到登录页
            break;
            // 其他状态码处理...
          case HTTP_STATUS.FORBIDDEN:
            message = '没有权限访问该资源';
            break;
            // ...其他case
        }
      }

      ElMessage.error(message);
      return Promise.reject(error);
    }
);

// 封装常用请求方法
export const request = {
  // GET请求
  get: (url, params, config = {}) => {
    return axiosInstance.get(url, { params, ...config });
  },

  // POST请求
  post: (url, data, config = {}) => {
    return axiosInstance.post(url, data, config);
  },

  // PUT请求
  put: (url, data, config = {}) => {
    return axiosInstance.put(url, data, config);
  },

  // DELETE请求
  delete: (url, config = {}) => {
    return axiosInstance.delete(url, config);
  },

  // PATCH请求
  patch: (url, data, config = {}) => {
    return axiosInstance.patch(url, data, config);
  },

  // 文件上传
  upload: (url, formData, config = {}) => {
    return axiosInstance.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      ...config
    });
  },

  // 文件下载
  download: (url, params, filename, config = {}) => {
    return axiosInstance.get(url, {
      params,
      responseType: 'blob',
      ...config
    }).then(response => {
      // 创建下载链接
      const blob = new Blob([response]);
      const downloadUrl = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(downloadUrl);
      return response;
    });
  },

  // 并发请求
  all: (requests) => {
    return axios.all(requests);
  },

  // 并发请求（带进度）
  allSettled: (requests) => {
    return axios.allSettled(requests);
  },

  // 取消请求
  cancel: (cancelToken) => {
    if (cancelToken) {
      cancelToken.cancel('请求已取消');
    }
  },

  // 创建取消令牌
  createCancelToken: () => {
    return axios.CancelToken.source();
  }
};

// 导出axios实例，以便直接使用
export { axiosInstance as axios };

export default request;
